package com.example.springtaskschedule.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.Locale;
import java.util.UUID;

/**
 * servlet 中的Filter，而非springfliterchain中的filter
 *
 * @author zhouxianfeng
 * @date 2021-4-15
 */
@WebFilter(filterName = "authFilter", urlPatterns = "/*")
@Order(1) //测试好像这个参数不生效，实际生效的是Filter扫描到的顺序（所以起名很重要）
public class StaticAttributeSetFilter implements Filter {

    private static final String key = "traceId";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        Locale locale = request.getLocale();
        //validator中的locale
        LocaleContextHolder.setLocale(locale, true);
        String traceId = MDC.get(key);
        if (StringUtils.isEmpty(traceId)) {
            MDC.put(key, UUID.randomUUID().toString().replace("-", ""));
        }
        chain.doFilter(request, response);
    }
}
